<style lang="scss">
.cus-data-source__insert {
  flex: 1;
}
</style>

<template>
  <template v-if="inited">
    <!--    {{widgetConfig.enums}}-->
<!--    {{state.value}}-->
<!--    <el-row>-->
<!--      <el-button @click="save">保存</el-button>-->
<!--    </el-row>-->
<!--    {{state.value.data}}-->
    <slot-com :defs="form_slot_content" :attrs="{}"
              name="cus_data_source__beforebegin" :binds="{
      ctx: exportCtx
              }"></slot-com>
<!--    <el-row class="a-space-mb-10 cus_data_source__item-title">-->
<!--      <div class="cus_data_source__label">标题</div>-->
<!--      <el-input  style="width: auto; flex: 1"-->
<!--                v-model="state.value.data.label" @blur="onBlur"></el-input>-->
<!--    </el-row>-->
<!--    <z-wang-textarea></z-wang-textarea>-->
<!--    {{state.testV2}}-->
    <h3 style="margin-top: 0; margin-bottom: 0">数据源</h3>
    <el-row class="a-space-mb-10">
      <el-select v-model="state.value.data.type"
        @change="onChangeType"
      >
        <el-option value="STATIC" label="固定"></el-option>
        <el-option value="API" label="接口"></el-option>
      </el-select>
    </el-row>
    <div v-for="(item, key) in state.value.data.obj">
      <div v-show="key === state.value.data.type">
        <template v-if="key === 'API'">
          <el-row class="a-space-mb-10">
            <el-select v-model="item.name"
                       @change="onChangeName(item.apis, $event)">
              <el-option :value="serverApi.option_label"
                         :label="serverApi.option_value"
              v-for="serverApi in state.serverApis"
              ></el-option>
            </el-select>
          </el-row>
<!--          {{item.apis[item.name].parameters}}-->
          <div v-if="state.reloaded">
            <div class="a-space-mb-10">
              <div style="margin-top: 0; margin-bottom: 0">参数</div>
              <div v-if="item.name && item.apis[item.name] && item.apis[item.name].parameters">
                <!--            {{item.apis[item.name]}}-->
                <div v-for="(param, paramIndex) in item.apis[item.name].parameters"
                     :key="paramIndex"
                >
                  <el-row class="a-space-mb-10" style="width: 100%">
                    <div style="width: 70px; text-align: right; padding-right: 10px">{{param.fieldName}}
                      <!--                  ({{param.fieldValue}})-->
                    </div>
                    <cus-insert-v2
                        con-class="cus-data-source__insert"
                        v-model="item.apis[item.name].parameters[paramIndex].fxValue"
                        :on-modal-closed="onV2ModalClosed"
                        :before-modal-opened="beforeInsertV2ModalOpened"
                        @modalClosed="onChangeObj"
                    ></cus-insert-v2>

                    <!--                <el-input v-model="item.apis[item.name].parameters[paramIndex].value"-->
                    <!--                          @change="onChangeObj"></el-input>-->
                  </el-row>
                </div>
              </div>
            </div>
<!--            -->
            <div class="a-space-mb-10">
              <div style="margin-top: 0; margin-bottom: 0">返回参数</div>
<!--              {{item.apis[item.name]}}-->
              <div v-if="item.name && item.apis[item.name] && item.apis[item.name].returnParameters">
                <!--            {{item.apis[item.name]}}-->
                <z-cell-item label="label字段" label-width="70px">
                  <el-select @change="onChangeObj" v-model="item.apis[item.name].returnUUID">
                    <el-option
                        v-for="item in item.apis[item.name].returnParameters"
                        :key="item.fieldValue"
                        :label="item.fieldName"
                        :value="item.fieldValue"
                    />
                  </el-select>
                </z-cell-item>
                <z-cell-item label="值字段"  label-width="70px">
                  <el-select @change="onChangeObj" v-model="item.apis[item.name].returnValueUUID">
                    <el-option
                        v-for="item in item.apis[item.name].returnParameters"
                        :key="item.fieldValue"
                        :label="item.fieldName"
                        :value="item.fieldValue"
                    />
                  </el-select>
                </z-cell-item>
<!--                <div v-for="(param, paramIndex) in item.apis[item.name].paramList"-->
<!--                     :key="paramIndex"-->
<!--                >-->
<!--                  <el-row class="a-space-mb-10" style="width: 100%">-->
<!--                    <div>{{param.comments}}-->
<!--                      &lt;!&ndash;                  ({{param.fieldValue}})&ndash;&gt;-->
<!--                    </div>-->
<!--&lt;!&ndash;                    <cus-insert-v2&ndash;&gt;-->
<!--&lt;!&ndash;                        con-class="cus-data-source__insert"&ndash;&gt;-->
<!--&lt;!&ndash;                        v-model="item.apis[item.name].paramList[paramIndex].fxValue"&ndash;&gt;-->
<!--&lt;!&ndash;                        :on-modal-closed="onV2ModalClosed"&ndash;&gt;-->
<!--&lt;!&ndash;                        :before-modal-opened="beforeInsertV2ModalOpened"&ndash;&gt;-->
<!--&lt;!&ndash;                        @modalClosed="onChangeObj"&ndash;&gt;-->
<!--&lt;!&ndash;                    ></cus-insert-v2>&ndash;&gt;-->

<!--                    <el-input v-model="item.apis[item.name].paramList[paramIndex].value"-->
<!--                              @change="onChangeObj"></el-input>-->
<!--                  </el-row>-->
<!--                </div>-->
              </div>
            </div>
          </div>
<!--          <div>-->
<!--            <el-button size="small" @click="appendApi(key)">添加</el-button>-->
<!--          </div>-->
        </template>
        <template v-else>
<!--          {{state.OPT.widgetConfig}}-->
          <template v-if="state.OPT.widgetConfig">
            <div v-if="state.reloaded">
              <cus-opt-manager
                  v-if="state.OPT.widgetConfig.staticType === 'options'"
                  :ui="staticManager.config.option.ui"
                  v-model="item.value"
                  @valuechange="onValueChange(item, 'value', $event)"
              ></cus-opt-manager>
              <cus-opt-manager
                  v-if="state.OPT.widgetConfig.staticType === 'multi-options'"
                  :ui="staticManager.config.checkbox.ui"
                  v-model="item.value"
                  @valuechange="onValueChange(item, 'value', $event)"
              ></cus-opt-manager>
              <!--            <el-row class="a-space-mb-10">-->
              <!--              <el-input v-model="item.name" @change="onChangeObj"></el-input>-->
              <!--            </el-row>-->
            </div>
          </template>
        </template>
      </div>
    </div>
  </template>

</template>

<script>
import {CustomRenderControlMixin, defineCustomRender} from "@/plugins/form-render/utils/index.js";
import {inject, nextTick, onMounted, reactive, toRaw} from "vue";
import ZEasyModal from "@/plugins/z-frame/components/ZEasyModal.vue";
import ZWangTextarea from "@/plugins/z-frame/ZWangTextarea.vue";
import CusInsertV2 from "@/plugins/form-render/CusInsertV2.vue";
import {getInterfaceList} from "@/hooks/api";
import CusOptManager from "@/plugins/form-render/components/CusOptManager.vue";
import ZCellItem from "@/plugins/z-frame/components/ZCellItem.vue";

export default {
  name: 'CusDataSource',
  components: {ZCellItem, CusOptManager, CusInsertV2, ZEasyModal,ZWangTextarea},
  mixins: [
    CustomRenderControlMixin
  ],
  setup(props, ctx) {

    let {part_key} = props.defs;

    let ZDragxmlInstance = inject('ZDragxmlInstance')

    // console.log(insVars)

    function parseCachedData(obj) {
      if (!obj.data) {
        obj.data = {
          obj: {}
        }
      }
    }

    let obj;
    let JSON5 = ZY.JSON5;
    let { data, methods, listeners, init, widgetConfig2, curFormCon, setModelVal } = defineCustomRender(props, ctx, {
      handleValueInit(newVal) {
        // console.log('CusUI', newVal, typeof  newVal)
        if (!newVal) {
          newVal = {
            // classObj: {},
            // attrsObj: {},
            control: {
              propsV2: {}
            },
            data: {
              obj: {}
            }
          }
          return newVal
        }
        if (newVal) {
          try {
            obj = JSON5.parse(newVal)
            // console.log(obj)
            parseCachedData(obj)

            return obj
          } catch (e) {
            console.log(e)
          }
        }
        return {}
      }
    })
    let state = data({
      reloaded: true,
      value: {},
      // testV2: '',
      testV2: ZY.JSON5.stringify({
        "funcs": [
          [
            "return `${VAL}<xy-text text-item level=\"${INDEX}\" val=\"M(['field__wXOpYQ4_oP'])\" type-field=\"\" >多行文本</xy-text>`"
          ],
          [
            "return `${VAL}<xy-text text-item level=\"${INDEX}\">)</xy-text>`"
          ]
        ],
        "textContent": "M(['field__wXOpYQ4_oP']))"
      }),
      currentServerApi: null,
      serverApis: []
    })
    init(props)

    function getCachedVal() {
      let clonedValue = JSON5.parse(JSON5.stringify(state.value))
      // console.log(clonedValue)
      Reflect.deleteProperty(clonedValue, 'control')
      return clonedValue
    }

    function onChange() {
      let str = JSON5.stringify(getCachedVal())
      // console.log('onChaneg')
      methods.onChange(str)
      // curFormCon.comManager.context.sendEvent('save:form', {
      //
      // })
      // curFormCon.comManager.context.sendEvent('save:cusui', {
      //   str
      // })
    }

    function save() {
      onChange()
    }

    function onBlur() {
      // console.log('onBlur')
      onChange()
    }

    let propsState = reactive({
      props: {}
    })

    function setPropVal(props, key, e) {
      props[key] = e
      let obj = toRaw(props)
      state.value.data.attrs = Object.entries(obj)


      // console.log('setPropVal', obj, key, e, state.value.data.attrs );
      curFormCon.callPageEvent('cus_data_source__set-prop-val', {
        props: obj, key, value: obj[key]
      }, e);
      nextTick(() => {
        onBlur()
      })
    }

    // function appendApi(key) {
    //   state.value.data.obj[key].apis.push({
    //     name: '',
    //     parameters: [
    //     ]
    //   })
    // }

    function initServerApis() {
      getInterfaceList({}, {}).then(res => {
        // console.log(res)
        if (Array.isArray(res)) {
          state.serverApis = res.map(v => {
            v.option_label = v.interfaceName
            v.option_value = v.interfaceName
            return v
          })
        }
      })
    }

    /**
     * 当数据源类型改变时
     * @param newType
     */
    function onChangeType(newType) {
      console.log('state.value.data.type', newType)
      if (newType === 'API') {
        initServerApis()
        if (!state.value.data.obj[newType]) {
          state.value.data.obj[newType] = {
            apis: {}
          }
        }
      }
      if (newType === 'STATIC') {
        if (!state.value.data.obj[newType]) {
          state.value.data.obj[newType] = {
            value: '',
            name: ''
          }
        }
      }
      onChange()
    }

    /**
     * onChangeName
     */
    function onChangeName(apis, newApiName) {
      // let parameters = state.value.data.obj[newVal].parameters
      let serverApi = state.serverApis.find(v => {
        return v.option_value === newApiName
      })
      console.log('onChangeName', apis, serverApi)
      let rawApi =  toRaw(serverApi)
      let returnRawParamas = toRaw(serverApi.returnParameters)
      if (!Array.isArray(returnRawParamas)) {
        returnRawParamas = []
      }
      let rawParams = toRaw(serverApi.parameters) ?? []

      // 获取每个接口的参数列表
      if (!apis[newApiName]) {
        apis[newApiName] = {
          origin: toRaw(serverApi),
          parameters: rawParams.map(v => {
            // fieldName: "dictName"
            // fieldValue: "String"
            return v
          }),
          returnUUID: '',
          returnValueUUID: '',
          returnParameters: returnRawParamas.map(v => {
            // fieldName: "dictName"
            // fieldValue: "String"
            return v
          }),
        }
      }  else {
        let cached = toRaw(apis[newApiName])
        let oldParams = toRaw(apis[newApiName].parameters) ?? []
        let newParams = toRaw(serverApi.parameters) ?? []

        let oldP = toRaw(apis[newApiName].returnParameters) ?? []
        let newP = toRaw(serverApi.returnParameters) ?? []
        apis[newApiName] = {
          origin: toRaw(serverApi),
          returnUUID: cached.returnUUID,
          returnValueUUID: cached.returnValueUUID,
          parameters: newParams.map(newParam => {
            let oldParam = oldParams.find(v => v.fieldName === newParam.fieldName)
            if (oldParam) {
              return Object.assign(newParam, oldParam)
            }
            // fieldName: "dictName"
            // fieldValue: "String"
            return newParam
          }),
          returnParameters: newP.map(newParam => {
            let oldParam = oldP.find(v => v.fieldName === newParam.fieldName)
            if (oldParam) {
              return Object.assign(newParam, oldParam)
            }
            // fieldName: "dictName"
            // fieldValue: "String"
            return newParam
          }),
        }
        console.log( oldParams, newParams, apis[newApiName] )
      }

      state.currentServerApi = apis[newApiName]
      state.reloaded = false
      setTimeout(() => {
        state.reloaded = true;
        onChange()
      }, 1000)
      // onChange()
    }

    /**
     * 当每个obj改变时
     */
    function onChangeObj() {
      onChange()
    }

    onMounted(() => {
      initServerApis()
    })

    let exportCtx = {
      getExportData() {
        return getCachedVal()
      },
      importData(data) {
        setModelVal(JSON5.stringify(data))
        nextTick(() => {
          onChange()
          curFormCon.callPageEvent('cus_data_source__import_data', {
            props: obj,
          }, {});
        })
      }
    }

    function beforeInsertV2ModalOpened({toolState}) {
      // console.log('beforeInsertV2ModalOpened', toolState)
      let insVars = ZDragxmlInstance.getInsVars()
      toolState.insertedVars = [].concat(
          insVars
      )
    }

    function onV2ModalClosed({getText}) {
      // let textObj = getText()
      // console.log('onV2ModalClosed', textObj)
    }

    function onValueChange(obj, key, newVal) {
      // console.log('onValueChange', newVal)
      obj[key] = newVal
      nextTick(() => {
        onChange()
      })
    }

    let staticManager = {}
    staticManager.config = {}
    staticManager.config.option = {
      ui: {
        widgetConfig: {
          mounted: true
        }
      }
    }
    staticManager.config.checkbox = {
      ui: {
        widgetConfig: {
          mounted: true,
          multi: true
        }
      }
    }

    return {
      state,
      widgetConfig: widgetConfig2,
      onChange,
      methods,
      propsState,
      staticManager,
      // appendApi,
      onChangeType,
      onValueChange,
      beforeInsertV2ModalOpened,
      onV2ModalClosed,
      onChangeName,
      onChangeObj,
      exportCtx,
      // onAttrsChange,
      // onClassChange,
      setPropVal,
      onBlur,
      save,
      listeners,
    }
  },
}
</script>

